#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <cerrno>

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        std::cerr << "fcntl error" << std::endl;
        return;
    }

    fcntl(fd, F_SETFL, fd | O_NONBLOCK);
}

int main()
{
    // 将标准输入设置为非阻塞状态
    SetNonBlock(0);
    while (1)
    {
        /* code */
        errno = 0;
        char buffer[1024];
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if (s < 0)
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
                std::cout << "data is not ready, errno = " << errno << std::endl;

            sleep(1);
        }
        else
        {
            buffer[s] = 0;
            write(1, buffer, strlen(buffer));
            std::cout << "read success, errno = " << errno << std::endl;
        }
    }

    return 0;
}